package chapter14.Collection.Set.Exercise;

import java.util.HashSet;
import java.util.Objects;

/**
 * @Auther: Tx
 * @Date: 2022/5/11 23:30
 */
@SuppressWarnings("all")
public class Ex02 {
    public static void main(String[] args) {
        MyDate birthday = new MyDate("1999","5","21");
        MyDate birthday1 = new MyDate("1999","5","21");
        Employ employ = new Employ("tom",10000.5,birthday);
        Employ employ1 = new Employ("tom",100.5,birthday1);
        HashSet set = new HashSet();
        set.add(employ);
        set.add(employ1);
        System.out.println(set);
    }
}

class Employ {
private String name;
private double sal;
private MyDate birthday;

    public Employ(String name, double sal, MyDate birthday) {
        this.name = name;
        this.sal = sal;
        this.birthday = birthday;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employ employ = (Employ) o;
        return this.name==employ.name&&this.birthday.equals(employ.birthday);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, birthday);
//         for (Object element : a)
//            result = 31 * result + (element == null ? 0 : element.hashCode());
//            源码中会根据动态绑定机制，调用对应的hashCode方法()
    }

    @Override
    public String toString() {
        return "Employ{" +
                "name='" + name + '\'' +
                ", sal=" + sal +
                ", birthday=" + birthday.toString() +
                '}';
    }
}

class MyDate {
    private String year;
    private String month;
    private String day;

    public MyDate(String year, String month, String day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        MyDate myDate = (MyDate) o;
        return this.year==myDate.year&&this.month==myDate.month&&this.day==myDate.day;
    }

    @Override
    public String toString() {
        return "MyDate{" +
                "year='" + year + '\'' +
                ", month='" + month + '\'' +
                ", day='" + day + '\'' +
                '}';
    }

    @Override
    public int hashCode() {
        return Objects.hash(year, month, day);
    }
}